import time
from selenium import webdriver
import ddddocr
import requests
from hashlib import md5
from selenium.webdriver import ActionChains


class Chaojiying_Client(object):

    def __init__(self, username, password, soft_id):
        self.username = username
        password = password.encode('utf8')
        self.password = md5(password).hexdigest()
        self.soft_id = soft_id
        self.base_params = {
            'user': self.username,
            'pass2': self.password,
            'softid': self.soft_id,
        }
        self.headers = {
            'Connection': 'Keep-Alive',
            'User-Agent': 'Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 5.1; Trident/4.0)',
        }

    def PostPic(self, im, codetype):
        """
        im: 图片字节
        codetype: 题目类型 参考 http://www.chaojiying.com/price.html
        """
        params = {
            'codetype': codetype,
        }
        params.update(self.base_params)
        files = {'userfile': ('ccc.jpg', im)}
        r = requests.post('http://upload.chaojiying.net/Upload/Processing.php', data=params, files=files,
                          headers=self.headers)
        return r.json()

    def PostPic_base64(self, base64_str, codetype):
        """
        im: 图片字节
        codetype: 题目类型 参考 http://www.chaojiying.com/price.html
        """
        params = {
            'codetype': codetype,
            'file_base64': base64_str
        }
        params.update(self.base_params)
        r = requests.post('http://upload.chaojiying.net/Upload/Processing.php', data=params, headers=self.headers)
        return r.json()

    def ReportError(self, im_id):
        """
        im_id:报错题目的图片ID
        """
        params = {
            'id': im_id,
        }
        params.update(self.base_params)
        r = requests.post('http://upload.chaojiying.net/Upload/ReportError.php', data=params, headers=self.headers)
        return r.json()


chaojiying = Chaojiying_Client("567wlq", "2xli4c8k", "971380")
ocr = ddddocr.DdddOcr()

options = webdriver.ChromeOptions()
options.add_argument("--user-data-dir=C:/Users/20486/AppData/Local/Google/Chrome/User Data/Default")
options.add_experimental_option('excludeSwitches', ['enable-automation'])
options.add_argument("--disable-blink-features=AutomationControlled")
driver = webdriver.Chrome(options=options)
driver.maximize_window()
driver.get("https://jzsc.mohurd.gov.cn/data/company")
time.sleep(3)

counter = 0
while True:
    button_list = driver.find_elements("xpath", "//div[@class='cell']/span[@class='link']")
    count = len(button_list)
    if count > 0:
        count -= 1
        for button in button_list:
            try:
                # 点击当前按钮
                button.click()
                counter += 1
                # 切换到新打开的标签页
                driver.switch_to.window(driver.window_handles[-1])
                time.sleep(3)
                # 检查是否有验证码
                # print(len(driver.find_elements("xpath", "//div[@class='el-dialog__body']/span")))
                if len(driver.find_elements("xpath", "//div[@class='el-dialog__body']/span")) > 0:
                    print(f"第{counter}个企业遇到验证码，尝试识别...")
                    click_button = driver.find_element("xpath",
                                                       "//div[@class='dialog-footer']/button[contains(@class,'el-button el-button--red')]")
                    click_button.click()
                    for i in range(3):
                        try:
                            code_element = driver.find_element("xpath", "//div[@class='geetest_widget']")
                            code_element.screenshot("建筑市场.png")
                            im = open('建筑市场.png', 'rb').read()
                            xy_list = chaojiying.PostPic(im, 9004)["pic_str"]
                            print(xy_list)
                            for xy in xy_list.split("|"):
                                x, y = xy.split(",")
                                x = int(x)
                                y = int(y)
                                ActionChains(driver).move_to_element_with_offset(code_element, x, y).click().perform()
                                time.sleep(0.5)
                            driver.find_element("xpath", "//div[@class='geetest_commit_tip']").click()
                            time.sleep(5)
                            # 检查是否验证成功
                            if len(driver.find_elements("xpath", "//h3[@class='detaile-header__title mb20']")) > 0:
                                print("验证码识别成功！")
                                break
                            else:
                                print(f"第{i + 1}次验证失败，准备重试...")
                        except Exception as e:
                            print(f"验证码处理第{i + 1}次出错:", str(e))
                            time.sleep(2)
                            if i == 2:  # 最后一次尝试失败
                                print("验证码识别失败，跳过此页面")
                                driver.close()
                                driver.switch_to.window(driver.window_handles[0])
                                continue  # 跳过当前按钮的后续处理
                name = driver.find_element("xpath",
                                           "//h3[@class='detaile-header__title mb20']/span[@class='name']").text
                cid = driver.find_element("xpath", "//div[@class='el-col el-col-14']/div[@class='value']").text
                position = driver.find_element("xpath", "//div[@class='el-col el-col-24']/div[@class='value']").text
                user_name = driver.find_element("xpath", "//div[@class='el-col el-col-10']/div[@class='value']").text
                print(counter, name, cid, position, user_name)
                # 关闭当前标签页并切换回主标签页
                driver.close()
                driver.switch_to.window(driver.window_handles[0])
                time.sleep(2)
            except Exception as e:
                print(f"处理元素时出错: {e}")
                # 确保无论如何都回到主标签页
                if len(driver.window_handles) > 1:
                    driver.close()
                    driver.switch_to.window(driver.window_handles[0])
    # 尝试翻页
    try:
        next_button = driver.find_element("xpath", "//button[@class='btn-next']")
        if "disabled" in next_button.get_attribute("class"):
            print("已到达最后一页，结束爬取")
            break
        next_button.click()
        time.sleep(3)  # 等待页面加载
    except Exception as e:
        print(f"翻页时出错: {e}")
        break
